package se.perp.c4.ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import se.perp.c4.control.iface.ICancellable;

public class CancellableWaitDialog extends JDialog implements ActionListener {

    private JButton cancelButton;
    private boolean wasCanceled = false;
    private ICancellable cancellable = null;

    public CancellableWaitDialog(Window owner, Rectangle centerInside, String message, String caption) {
        super(owner);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        setTitle(caption);

        cancelButton = new JButton("Cancel");
        cancelButton.setMnemonic('C');
        cancelButton.addActionListener(this);

        setLayout(new BorderLayout());

        JPanel centerPanel = new JPanel();
        GridBagLayout gb = new GridBagLayout();
        GridBagConstraints gc = new GridBagConstraints();
        centerPanel.setLayout(gb);

        ImagePanel ip = new ImagePanel(Images.get(Images.Which.GLOBE));
        gc.anchor = GridBagConstraints.WEST;
        gc.fill = GridBagConstraints.NONE;
        gc.ipadx = 15;
        gc.insets = new Insets(10, 10, 0, 0);
        centerPanel.add(ip, gc);

        JLabel lbl = new JLabel(message);

        gc.anchor = GridBagConstraints.EAST;
        gc.fill = GridBagConstraints.REMAINDER;

        centerPanel.add(lbl,gc);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(cancelButton);

        add(centerPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        pack();

        int x = owner.getX() + centerInside.x + (centerInside.width - getWidth()) / 2;
        int y = owner.getY() + centerInside.y + (centerInside.height - getHeight()) / 2;

        setLocation(x, y);

    }

    public void setCancellableOperation(ICancellable c) {
        cancellable = c;
    }

    public boolean wasCanceled() {
        return wasCanceled;
    }

    public void actionPerformed(ActionEvent e) {
        wasCanceled = true;
        setVisible(false);
        if (cancellable != null) {
            cancellable.cancel();
        }
    }
}
